//
//  ViewController.swift
//  YOKO
//
//  Created by Zoe_G on 16/5/1.
//  Copyright © 2016年 15Tec. All rights reserved.
//

import UIKit
import SnapKit
import RealmSwift

let screenWidth = UIScreen.mainScreen().bounds.size.width
let screenHeight = UIScreen.mainScreen().bounds.size.height

class ViewController: UIViewController, MonthSelectorViewDelegate , MonthViewControllerDelegate, DayViewControllerDelegate, WeekViewControllerDelegate{
    
    //MARK: - monthVC
    var monthVC: MonthViewController? = nil
    
    //MARK: - dayVC
    var dayVC: DayViewController? = nil
    
    //MARK: - weekVC
    var weekVC: WeekViewController? = nil
    
    var nowShowingViewTag: Int = 0 //0 表示 MonthView, 1 表示 WeekView, 2表示DayView
    
    //MARK: - calendarSelectorVC
    var calendarView: CalendarView!
    var calendarViewModel: CalendarViewModel!
    var calendarViewBottomConstraint: Constraint! //calendarSelectorTopConstraint的顶层约束，用来实现动画效果
    var calendarViewState: Int = 0 {
        /// calendarSelectorView的展示状态，0表示展示的状态，1表示不展示的状态
        didSet {
            if calendarViewState == 1 {
                //如果要展示
                
                //monthSelectorView可能会出现，因此先隐藏它，让它立即执行，不要出现动画
                if monthSelectorViewState == 1 {
                    UIView.setAnimationsEnabled(false)
                    monthSelectorViewState = 0
                    UIView.setAnimationsEnabled(true)
                }
                
                //如果已经被隐藏了，那么取消隐藏并且从顶部滑下来
                //并且设置dimView为不隐藏
                //calendarSelectorVC.view.hidden = false
                dimView.hidden = false
                
                //由于必须浮动于最上方，因此更改self.view的UIView的排布顺序
                self.view.bringSubviewToFront(dimView)
                self.view.bringSubviewToFront(calendarView)
                
                UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.7, options: .CurveEaseInOut, animations:
                    {
                        () -> Void in
                        self.calendarViewBottomConstraint.updateOffset(self.calendarView.frame.height - 5.0) //由于已经layoutSubview过了yinciself.calendarSelectorVC.view.frame.height是正确的,偏移量是为了隐藏掉弹性动画
                        self.view.layoutIfNeeded()
                    }, completion: nil)
            }
            else {
                //如果要隐藏
                UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.7, options: .CurveEaseInOut, animations:
                    {
                        self.calendarViewBottomConstraint.updateOffset(0.0)
                        self.view.layoutIfNeeded()
                    }, completion:
                    { (complete) in
                        //隐藏两个
                        //self.calendarSelectorVC.view.hidden = true
                })
                self.dimView.hidden = true //直接隐藏，不经过动画
            }
        }
    }
    
    //MARK: - monthSelector
    var monthSelectorView: MonthSelectorView! //日历选择的tabBarButton
    var monthSelectorViewTopConstraint: Constraint! //日历的顶部约束
    var monthSelectorViewState: Int = 0 { //0表示隐藏状态，1表示显示的状态
        didSet {
            if monthSelectorViewState == 1 {
                //如果calendarSelectorVC.view还没有隐藏那么隐藏
                if (calendarViewState == 1) {
                    UIView.setAnimationsEnabled(false)
                    calendarViewState = 0
                    UIView.setAnimationsEnabled(true)
                }
                
                //展示状态
                monthSelectorView.hidden = false
                dimView.hidden = false
                self.view.bringSubviewToFront(dimView)
                self.view.bringSubviewToFront(monthSelectorView)
            }
            
            let newOffset: CGFloat = monthSelectorViewState == 0 ? -200 : -5
            UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.7, options: .CurveEaseInOut, animations:
                {
                    () -> Void in
                    NSLog("selectMonthView Animation withState=%i",self.monthSelectorViewState)
                    self.monthSelectorViewTopConstraint.updateOffset(newOffset)
                    self.view.layoutIfNeeded()
                }, completion: {
                    complete in
                    if self.monthSelectorViewState == 0 {
                        self.monthSelectorView.hidden = true
                    }
            })
            
            if monthSelectorViewState == 0 {
                //隐藏状态
                dimView.hidden = true
            }
        }
    }
    
    //navigation的状态栏
    var addBarButtonItem: UIBarButtonItem!
    var menuBarButtonItem: UIBarButtonItem!
    var monthSelectorBarButtonItem: UIBarButtonItem!
    var monthSelectorYearLabel: UILabel!
    var monthSelectorMonthLabel: UILabel!
    var navigationTitleView: NavigationTitleView!
    
    var dimView: UIView! //用来降低背景的UIView
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //初始化UI
        __addNavigationUI()
        
        //add childView (monthVC dayVC weekVC)
        self.monthVC = MonthViewController()
        monthVC?.delegate = self
        self.addChildViewController(self.monthVC!)
        self.view.addSubview((self.monthVC?.view)!)
        
        self.dayVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("DayViewController") as? DayViewController
        dayVC?.delegate = self
        self.addChildViewController(self.dayVC!)
        
        self.weekVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("WeekViewController") as? WeekViewController
        self.weekVC?.delegate = self
        self.addChildViewController(self.weekVC!)

        
        //初始化dimView和monthSelectorView
        //初始化dimView
        dimView = UIView()
        dimView.backgroundColor = UIColor(white: 0.0, alpha: 0.3)
        dimView.hidden = true
        self.view.addSubview(dimView)
        dimView.snp_makeConstraints {
            make in
            make.edges.equalTo(self.view)
        }
        let dimViewTapGestureHandler = UITapGestureRecognizer(target: self, action: #selector(ViewController.dimViewTapGestureHandler(_:)))
        dimView.addGestureRecognizer(dimViewTapGestureHandler)
        
        //初始化monthSelectorView
        monthSelectorView = NSBundle.mainBundle().loadNibNamed("MonthSelectorView", owner: self, options: nil).filter({$0 is MonthSelectorView}).last! as! MonthSelectorView
        monthSelectorView.delegate = self
        monthSelectorView.hidden = true
        monthSelectorView.currentYear = NSDate().year
        monthSelectorView.currentMonth = NSDate().month
        self.view.addSubview(monthSelectorView)
        monthSelectorView.snp_makeConstraints {
            make in
            make.left.equalTo(self.view)
            make.right.equalTo(self.view)
            monthSelectorViewTopConstraint = make.top.equalTo(self.snp_topLayoutGuideBottom).offset(-140).constraint
            make.height.equalTo(140)
        }

        //MARK: - Register notification
//        let realm = try! Realm()
//        notificationToken = realm.addNotificationBlock {
//            notification, realm in
//            print("Catchl")
//            //self.calendarSelectorVC.reinit()
//        }
        
//        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.changeCalendarIDNotificationHandler), name: YOKONotification.CHANGE_CURRENT_CALENDAR, object: nil)
//        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.loginOrOutHandler), name: YOKONotification.UPDATE_ALL_CALENDARS, object: nil)

        // Do any additional setup after loading the view, typically from a nib.
    }
    
    
    //var notificationToken: NotificationToken?
    
    deinit {
        //NSNotificationCenter.defaultCenter().removeObserver(self, name: nil, object: nil)
        //notificationToken?.stop()
    }
    
    //MARK: - Handler
    func addNewEventAction() {
        //导航栏右侧的+按钮的handler
        let newEventVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("NewEventViewController") as? NewEventViewController
        self.navigationController?.pushViewController(newEventVC!, animated: true)
        
    }
    
    func menuBarButtonItemHandler() {
        //导航栏左侧的menu菜单的handler
        if let slideContainer = self.navigationController?.parentViewController as? SlideViewController {
            switch slideContainer.slideState {
            case .SlidedIn:
                slideContainer.slideOut()
            case .SlidedOut:
                slideContainer.slideIn()
            }
        }
    }
    
    func monthSelectorBarButtonItemHandler() {
        //导航栏左侧的月份选择的handler
        //这里使用一种tricky的方法，通过判断weekVC.view和monthVC.view哪一个比较靠前来恢复到原来的状态
        switch nowShowingViewTag {
        case 0: //当前是MonthView
            break
        case 1: //当前是WeekView
            WeekViewbackToMonthViewController()
        case 2: //当前是DayView
            DayViewbackToMonthViewController()
        default:
            break
        }
        
        monthSelectorViewState = 1 - monthSelectorViewState
    }
    
    func dimViewTapGestureHandler(gesture: UITapGestureRecognizer) {
        //暗下来的背景点击需要隐藏月份选择View
        if calendarViewState == 1 {
            calendarViewState = 0
        }
        else if monthSelectorViewState == 1 {
            monthSelectorViewState = 0
        }
    }
    
    func navigationTitleTapHandler() {
        /**
         点击navigationTitle的触发函数，在下面的实现当中展示或者隐藏CalendarSelectorViewController的View
         通过更改calendarViewState来实现
         
         - parameter gesture: 触发的手势
         */
        calendarViewState = 1 - calendarViewState
    }
    
    func changeCalendarIDNotificationHandler() {
        /**
         更改当前Calendar的Handler
         */
        navigationTitleView.title = Config.getCurrentCalendar().summary ?? "未知"
    }
    
    //MARK: - MonthSelectorView代理函数
    func monthSelectorViewDidSelected(month month: Int, year: Int) {
        print("\(#function) --> month: \(month) year: \(year)")
        
        
        monthVC?.selectMonth(year, month: month)
        
        monthSelectorViewState = 1 - monthSelectorViewState
        setNavigationBarDate(String(format: "%i", year), month: String(format: "%i月", month))

    }
    
    //设置navigation的年月日期
    func setNavigationBarDate(year: String, month: String){
    
        monthSelectorMonthLabel.text = month
        monthSelectorYearLabel.text = year
        
    }
    
    //添加UI部分
    private func __addNavigationUI() {
        //导航栏的背景色
        if let navigationController = self.navigationController {
            
            navigationController.navigationBar.tintColor = UIColor.whiteColor()
            navigationController.navigationBar.barTintColor = YOKOColor.TypeColors[0]
            navigationController.navigationBar.translucent = false
            navigationController.navigationBar.hideBottomHairline()
            
        }
        
        //添加按钮
        let addBarButtonItemInnerButton = UIButton(type: .Custom)
        addBarButtonItemInnerButton.setImage(UIImage(named: "nav_icon_add"), forState: .Normal)
        addBarButtonItemInnerButton.frame = CGRectMake(0.0, 0.0, 20.0, 20.0)
        addBarButtonItemInnerButton.addTarget(self, action: #selector(ViewController.addNewEventAction), forControlEvents: .TouchUpInside)
        addBarButtonItem = UIBarButtonItem(customView: addBarButtonItemInnerButton)
        self.navigationItem.rightBarButtonItem = addBarButtonItem
        
        let menuBarButtonItemInnerButton = UIButton(type: .Custom)
        menuBarButtonItemInnerButton.setImage(UIImage(named: "nav_icon_menu"), forState: .Normal)
        menuBarButtonItemInnerButton.addTarget(self, action: #selector(ViewController.menuBarButtonItemHandler), forControlEvents: .TouchUpInside)
        menuBarButtonItemInnerButton.frame = CGRectMake(0.0, 0.0, 20.0, 20.0)
        menuBarButtonItem = UIBarButtonItem(customView: menuBarButtonItemInnerButton)
        
        //添加navigation的title
        navigationTitleView = NavigationTitleView(frame: CGRectMake(0.0, 0.0, 75.0, 35.0))
        navigationTitleView.maxWords = 6
        navigationTitleView.title = Config.getCurrentCalendar().summary ?? "未知"
        navigationTitleView.backgroundColor = YOKOColor.TypeColors[0]
        let navigationTitleTapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.navigationTitleTapHandler))
        navigationTitleView.addGestureRecognizer(navigationTitleTapGesture)
        
        //初始化calendarView
        self.calendarView = NSBundle.mainBundle().loadNibNamed("CalendarView", owner: self, options: nil).last as! CalendarView
        calendarViewModel = CalendarViewModel(viewController: self, calendarView: calendarView)
        
        self.view.addSubview(self.calendarView)
        self.calendarView.snp_makeConstraints {
            make in
            make.left.equalTo(self.view)
            make.right.equalTo(self.view)
            make.height.equalTo(200.0 / 570.0 * screenHeight + 55.0) //暂定为200
            self.calendarViewBottomConstraint = make.bottom.equalTo(self.snp_topLayoutGuideTop).constraint //处于隐藏的状态
        }
        //calendarView.hidden = true //初始的时候隐藏

        
        self.navigationItem.titleView = navigationTitleView
        
        //创建monthSelectorBarButtonItem
        monthSelectorMonthLabel = UILabel(frame: CGRectZero)
        monthSelectorMonthLabel.text = "10月"
        monthSelectorMonthLabel.textAlignment = .Right
        monthSelectorMonthLabel.textColor = UIColor.whiteColor()
        monthSelectorMonthLabel.font = UIFont.systemFontOfSize(14.0)
        monthSelectorMonthLabel.sizeToFit()
        
        monthSelectorYearLabel = UILabel(frame: CGRectMake(0.0, monthSelectorMonthLabel.frame.height, 0.0, 0.0))
        monthSelectorYearLabel.text = "0000"
        monthSelectorYearLabel.textColor = UIColor.whiteColor()
        monthSelectorYearLabel.font = UIFont.systemFontOfSize(8.0)
        monthSelectorYearLabel.sizeToFit()
        
        let monthSelectorExpandView = UIImageView(image: UIImage(named: "icon_展开2"))
        monthSelectorExpandView.frame = CGRectMake(monthSelectorYearLabel.frame.width + 3, monthSelectorMonthLabel.frame.height + 3, 4, 4)
        
        let monthSelectorBarButtonItemContainer = UIView(frame: CGRectMake(0, 0, 30.0, 30.0))
        let monthSelectorBarButtonFloatButton = UIButton(type: .Custom) //在ItemContainer顶层用来捕获事件
        monthSelectorBarButtonFloatButton.addTarget(self, action: #selector(ViewController.monthSelectorBarButtonItemHandler), forControlEvents: .TouchUpInside)
        monthSelectorBarButtonFloatButton.frame = monthSelectorBarButtonItemContainer.frame
        
        monthSelectorBarButtonItemContainer.addSubview(monthSelectorMonthLabel)
        monthSelectorBarButtonItemContainer.addSubview(monthSelectorExpandView)
        monthSelectorBarButtonItemContainer.addSubview(monthSelectorYearLabel)
        monthSelectorBarButtonItemContainer.addSubview(monthSelectorBarButtonFloatButton)
        
        monthSelectorBarButtonItem = UIBarButtonItem(customView: monthSelectorBarButtonItemContainer)
        
        let centerSpace = UIBarButtonItem(barButtonSystemItem: .FixedSpace, target: nil, action: nil)
        centerSpace.width = 20
        
        self.navigationItem.rightBarButtonItems = [addBarButtonItem]
        self.navigationItem.leftBarButtonItems = [menuBarButtonItem, centerSpace, monthSelectorBarButtonItem]
    }
    
    //MARK: - MonthViewControllerDelegate
    func monthViewControllerToDayViewController(date: NSDate, openUpHeight: CGFloat) {
        
        self.dayVC?.date = date
        CalendarAnimation.executeForwardsAnimation(self, fromView: (self.monthVC?.view)!, toView: (self.dayVC?.view)!, openUpHeight: openUpHeight)
        nowShowingViewTag = 2

    }
    
     //MARK: - DayViewControllerDelegate
    func DayViewbackToMonthViewController() {
        CalendarAnimation.executeReverseAnimation(self, fromView: (self.dayVC?.view)!, toView: (self.monthVC?.view)!)
        nowShowingViewTag = 0
    }
    
    func switchToWeekViewController(date: NSDate) {
        self.weekVC?.date = date
        self.view.addSubview((self.weekVC?.view)!)
        nowShowingViewTag = 1
    }
    
     //MARK: - WeekViewControllerDelegate
    func backToDayViewController() {
        self.weekVC?.view.removeFromSuperview()
        nowShowingViewTag = 2
    }
    
    func WeekViewbackToMonthViewController(){
        CalendarAnimation.executeReverseAnimation(self, fromView: (self.weekVC?.view)!, toView: (self.monthVC?.view)!)
        nowShowingViewTag = 0
    }
    
    //MARK: - CalendarSelectorViewController 处理函数
    
//    func calendarSelectorViewControllerInitCalendars(calendarVC: CalendarSelectorViewController) {
//        print("IN")
//        // 添加初始日历
//        let cals = uiRealm.objects(Calendar)
////        print("[")
//        for i in cals {
////            //print("$\(i.summary)$")
//            calendarSelectorVC.addCalendar(withUserInfo: i.calendarId, withName: i.summary, animated: false)
////            print("\t\(i.summary) --> \(i.calendarId)")
//        }
////        print("]\n")
//        
//        for singleCalendarView in calendarSelectorVC.calendarSelectorView.singleCalendarsViews {
//            if singleCalendarView.userInfo as? String == NSUserDefaults.getCurrentCalendarId() {
//                calendarSelectorVC.changeSelectedCalendar(toView: singleCalendarView)
//                break
//            }
//        }
//    }
    
//    func calendarSelectorViewControllerDidAddNewCalendar(calendarVC: CalendarSelectorViewController, forName name: String) {
//        // 添加一个日历本
//        let api = ApiSync()
//        let cal = Calendar()
//        cal.summary = name
//        cal.calendarId = String(NSDate().timeIntervalSince1970*1000)
//        cal.isLocal = true
//        //calendarVC.addCalendar(withStyle: .Custom, withUserInfo: cal.calendarId, withName: name)
//        try! uiRealm.write {
//            uiRealm.add(cal)
//        }
//        api.updateCalendarToServiceSync(cal, isAdd: true, callback: { (response, error) in
//            let cal_id = response!["data"]!["calendar_id"] as! String
//            try! uiRealm.write {
//                cal.calendarId = cal_id
//                cal.etag = response!["data"]!["calendarEntry"]!!["etag"] as! String
//            }
//            NSNotificationCenter.defaultCenter().postNotificationName(YOKONotification.UPDATE_ALL_CALENDARS, object: nil)
//        })
//        NSNotificationCenter.defaultCenter().postNotificationName(YOKONotification.UPDATE_ALL_CALENDARS, object: nil)
//    }
    
//    func calendarSelectorViewControllerDidTapCalendar(calendarVC: CalendarSelectorViewController, inView view: SingleCalendarView, withUserInfo userInfo: AnyObject?) {
//        //在这里的默认实现是更新Calendar的当前选择Calendar
//        calendarVC.changeSelectedCalendar(toView: view)
//        NSUserDefaults.setCurrentCalendarId(userInfo as! String)
//        
//        //如果需要在selector某一个以后隐藏起来，可以
//        calendarSelectorViewState = 0
//    }
    
//    func calendarSelectorViewControllerDidPressCalendarDeleteButton(calendarVC: CalendarSelectorViewController, inView view: SingleCalendarView, withUserInfo userInfo: AnyObject?, isCurrentSelectedView: Bool) {
//        //在这里默认实现是删除Calendar的view,如果当前选择的日历被删除了，那么跳转到主日历本
//        //calendarVC.deleteCalendar(view)
//        if isCurrentSelectedView == true {
//            //let mainCalendarView = calendarVC.calendarSelectorView.singleCalendarsViews.filter({ (view: SingleCalendarView) -> Bool in
//                //view.style == .Main
//            //}).last!
//            //calendarVC.changeSelectedCalendar(toView: mainCalendarView)
//            let sys_cal = uiRealm.objects(Calendar).filter("category = %@ AND source = %@", CATEGORY_SYSTEM, SOURCE_MAIN).first
//            NSUserDefaults.setCurrentCalendarId((sys_cal?.calendarId)!)
//        }
//        
//        let cal_id = userInfo as! String
//        let cal = uiRealm.objects(Calendar).filter("calendarId = %@", cal_id).first
//        try! uiRealm.write {
//            cal?.deleted = true
//        }
//        let api = ApiSync()
//        api.updateCalendarToServiceSync(cal!, isAdd: false, callback: { (response, error) in
////            let cal_id = response!["data"]!["calendar_id"] as! String
//            try! uiRealm.write {
//                uiRealm.delete(cal!)
//            }
//            NSNotificationCenter.defaultCenter().postNotificationName(YOKONotification.UPDATE_ALL_CALENDARS, object: nil)
//        })
//        
//        NSNotificationCenter.defaultCenter().postNotificationName(YOKONotification.UPDATE_ALL_CALENDARS, object: nil)
//    }
//    
//    func calendarSelectorViewControllerDidChangeNameForCalendar(calendarVC: CalendarSelectorViewController, toName name: String, inView view: SingleCalendarView, withUserInfo userInfo: AnyObject?) {
//        let calendarID = userInfo as! String
//        if let changeNameCalendar = uiRealm.objects(Calendar).filter("calendarId = %@", calendarID).last {
//            try! uiRealm.write {
//                changeNameCalendar.summary = name
//            }
//            let api = ApiSync()
//            api.updateCalendarToServiceSync(changeNameCalendar, isAdd: false, callback: { (response, error) in
////                let cal_id = response!["data"]!["calendar_id"] as! String
//                
//                NSNotificationCenter.defaultCenter().postNotificationName(YOKONotification.UPDATE_ALL_CALENDARS, object: nil)
//            })
//            if calendarID == NSUserDefaults.getCurrentCalendarId() {
//                navigationTitleView.title = name
//            }
//        }
//        else {
//            print("\(#function) --> Unable to find the calendar of calendar Id(\(calendarID))")
//        }
//    }
}